package com.slipper.system.ai.service;

import java.util.List;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.slipper.util.AffixUtil;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;

import com.slipper.system.ai.dao.KnowledgeFileDao;
import com.slipper.system.ai.bo.KnowledgeFileBO;

import com.slipper.core.transaction.ReadTransactional;
import com.slipper.core.transaction.WriteTransactional;
import com.slipper.util.Tool;
import com.slipper.util.UUID;

@Service
@ReadTransactional
public class KnowledgeFileService {
    @Resource
    private KnowledgeFileDao knowledgeFileDao;
    
    public KnowledgeFileBO queryBy(String id) {
        return knowledgeFileDao.queryBy(id);
    }
    
    public List<KnowledgeFileBO> queryList(KnowledgeFileBO bo) {
        return knowledgeFileDao.queryList(bo);
    }
    
    public PageInfo<KnowledgeFileBO> queryPage(KnowledgeFileBO bo) {
        PageHelper.startPage(bo.getPageNumber(), bo.getPageSize());
        return new PageInfo<>(knowledgeFileDao.queryList(bo));
    }
    
    @WriteTransactional
    public int save(KnowledgeFileBO bo) {
        if (Tool.isNotBlank(bo.getId())) {
            bo.setUpdateTime(System.currentTimeMillis());
            return knowledgeFileDao.update(bo);
        } else {
            bo.setId(UUID.getUUID());
            bo.setUpdateTime(System.currentTimeMillis());
            bo.setCreateTime(System.currentTimeMillis());
            return knowledgeFileDao.insert(bo);
        }
    }

    @WriteTransactional
    public void saveList(List<KnowledgeFileBO> list) {
        if (list == null) return;

        list.forEach(item -> {
            if (Tool.isNotBlank(item.getBase64())) {
                try {
                    item.setFileId(AffixUtil.saveFile(item.getName(), item.getBase64()));
                } catch (Exception e) {
                    throw new RuntimeException("文档保存出错！", e);
                }
            }
            if (knowledgeFileDao.queryBy(item.getId()) != null) {
                item.setUpdateTime(System.currentTimeMillis());
                knowledgeFileDao.update(item);
            } else {
                item.setUpdateTime(System.currentTimeMillis());
                item.setCreateTime(System.currentTimeMillis());
                knowledgeFileDao.insert(item);
            }
        });
    }
    
    @WriteTransactional
    public int delete(KnowledgeFileBO bo) {
        return knowledgeFileDao.delete(bo);
    }
}
